package com.galen.manual.config;

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.servers.Server;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.Collections;

/**
 * Swagger配置类
 * 使用SpringDoc OpenAPI 3
 */
@Configuration
public class SwaggerConfig {

    @Value("${server.servlet.context-path:}")
    private String contextPath;

    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(apiInfo())
                .servers(Arrays.asList(devServer(), prodServer()))
                .security(Collections.singletonList(securityRequirement()))
                .components(new io.swagger.v3.oas.models.Components()
                        .securitySchemes(Collections.singletonMap("Bearer Authentication", securitySchemes())));
    }

    /**
     * API信息
     */
    private Info apiInfo() {
        return new Info()
                .title("手工外发小程序API")
                .description("手工外发小程序后端服务接口文档")
                .version("1.0.0")
                .contact(new Contact()
                        .name("开发团队")
                        .email("dev@galen.com")
                        .url("https://www.galen.com"))
                .license(new License()
                        .name("MIT License")
                        .url("https://opensource.org/licenses/MIT"));
    }

    /**
     * 开发环境服务器
     */
    private Server devServer() {
        return new Server()
                .url("http://localhost:8080" + contextPath)
                .description("开发环境");
    }

    /**
     * 生产环境服务器
     */
    private Server prodServer() {
        return new Server()
                .url("https://api.galen.com" + contextPath)
                .description("生产环境");
    }

    /**
     * 安全要求
     */
    private SecurityRequirement securityRequirement() {
        SecurityRequirement requirement = new SecurityRequirement();
        requirement.addList("Bearer Authentication");
        return requirement;
    }

    /**
     * 安全方案
     */
    private SecurityScheme securitySchemes() {
        return new SecurityScheme()
                .type(SecurityScheme.Type.HTTP)
                .bearerFormat("JWT")
                .scheme("bearer")
                .in(SecurityScheme.In.HEADER)
                .name("Authorization")
                .description("JWT认证Token");
    }
}